package com.aurora.app.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.WebSocketSession;
import com.alibaba.fastjson.JSON;
import com.aurora.app.component.SocketSessionManager;
import com.aurora.app.entity.Chat;
import com.aurora.app.entity.ChatGroup;
import com.aurora.app.entity.Help;
import com.aurora.app.entity.HelpImage;
import com.aurora.app.entity.Thing;
import com.aurora.app.entity.ThingStory;
import com.aurora.app.entity.ThingStoryImage;
import com.aurora.app.entity.User;
import com.aurora.app.enums.UtTsType;
import com.aurora.app.exption.NullEntityException;
import com.aurora.app.service.ChatGroupService;
import com.aurora.app.service.ChatService;
import com.aurora.app.service.HelpImageService;
import com.aurora.app.service.HelpService;
import com.aurora.app.service.ThingImageService;
import com.aurora.app.service.ThingService;
import com.aurora.app.service.ThingStoryImageService;
import com.aurora.app.service.ThingStoryService;
import com.aurora.app.service.UserService;
import com.aurora.app.util.StandardResponseBody;

/**
 * 聊天
 * 
 * @author yongjiang.lin
 *
 */
@Controller
@RequestMapping("/api/chat")
public class ChatController {
	@Resource
	private UserService userService;
	@Resource
	private ThingService thingService;
	@Resource
	private ChatGroupService chatGroupService;
	@Resource
	private ChatService chatService;
	@Resource
	private SocketSessionManager socketSessionManager;
	@Resource
	private ThingImageService thingImageService;
	@Resource
	private ThingStoryImageService thingStoryImageService;
	@Resource
	private HelpService helpService;
	@Resource
	private ThingStoryService thingStoryService;
	@Resource
	private HelpImageService helpImageStoryService;

	/**
	 * 新建一个对话组
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "newChat")
	@ResponseBody
	public String newChatV2(HttpServletRequest request, String thingId, String helpId, String storyId) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		ChatGroup cg = null;
		User user = (User) request.getSession().getAttribute("user");
		// 新建关于闲置的聊天框
		if (StringUtils.isNotBlank(thingId)) {
			Thing thing = this.thingService.get(thingId);
			if (thing == null) {
				responseMap.put("STATUS", "ERR");
				responseMap.put("DESC", "闲置不存在");
				return JSON.toJSONString(responseMap);
			}
			cg = this.chatGroupService.getChatGroup(thing, null, null, user, UtTsType.UserThing);
		}
		// 新建关于帮帮的聊天框
		if (StringUtils.isNotBlank(helpId)) {
			Help help = helpService.get(helpId);
			if (help == null) {
				responseMap.put("STATUS", "ERR");
				responseMap.put("DESC", "帮帮任务不存在");
				return JSON.toJSONString(responseMap);
			}
			cg = this.chatGroupService.getChatGroup(null, null, help, user, UtTsType.Help);
		}
		// 新建关于物語的聊天框
		if (StringUtils.isNotBlank(storyId)) {
			ThingStory thingStory = thingStoryService.get(storyId);
			if (thingStory == null) {
				responseMap.put("STATUS", "ERR");
				responseMap.put("DESC", "帮帮任务不存在");
				return JSON.toJSONString(responseMap);
			}
			cg = this.chatGroupService.getChatGroup(null, thingStory, null, user, UtTsType.ThingStory);
		}

		responseMap.put("STATUS", "OK");
		responseMap.put("DESC", "返回成功");
		responseMap.put("GROUPID", cg.getId());
		return JSON.toJSONString(responseMap);
	}

	/**
	 * 废除
	 * 
	 * @param request
	 * @param thingId
	 * @return
	 */
	public String newChat(HttpServletRequest request, @RequestParam("THING_ID") String thingId) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		Thing thing = this.thingService.get(thingId);
		User user = (User) request.getSession().getAttribute("user");
		if (thing == null || user == null) {
			responseMap.put("STATUS", "ERR");
			responseMap.put("DESC", "请求参数有误");
			return JSON.toJSONString(responseMap);
		}
		ChatGroup cg = this.chatGroupService.getChatGroup(thing, null, null, user, UtTsType.UserThing);
		responseMap.put("STATUS", "OK");
		responseMap.put("DESC", "返回成功");
		responseMap.put("GROUPID", cg.getId());
		return JSON.toJSONString(responseMap);
	}

	/**
	 * 围绕二手物品的聊天
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "withThing")
	public ModelAndView withThingV2(HttpServletRequest request, @RequestParam("CHATGROUPID") String chatGroupId) {
		ModelAndView mv = null;
		ChatGroup cg = this.chatGroupService.getBaseDao().find(chatGroupId);
		Thing thing = null;
		ThingStory thingStory = null;
		Help help = null;
		if (cg != null) {
			switch (cg.getUtTsType()) {
			case UserThing:
				thing = cg.getThing();
				mv = new ModelAndView("chat/thing");
				break;
			case ThingStory:
				thingStory = cg.getThingStory();
				mv = new ModelAndView("chat/square");
				break;
			case Help:
				help = cg.getHelp();
				mv = new ModelAndView("chat/help");
				break;
			}
		} else {
			throw new NullEntityException();
		}
		List<Chat> cList = this.chatService.getListByGroupId(chatGroupId);
		User fUser = (User) request.getSession().getAttribute("user");
		User tUser = null;

		// 买家角度
		switch (cg.getUtTsType()) {
		case UserThing:
			// 卖家的角度
			if (fUser.getId().equals(thing.getUser().getId())) {
				tUser = cg.getUser();
			} else {
				tUser = thing.getUser();
			}
			break;
		case ThingStory:
			// 卖家的角度
			if (fUser.getId().equals(thingStory.getUser().getId())) {
				tUser = cg.getUser();
			} else {
				tUser = thingStory.getUser();
			}
			break;
		case Help:
			// 卖家的角度
			if (fUser.getId().equals(help.getUser().getId())) {
				tUser = cg.getUser();
			} else {
				tUser = help.getUser();
			}
			break;
		}

		switch (cg.getUtTsType()) {
		case UserThing:
			String thingImage = this.thingImageService.getFirstImageByThingId(thing.getId()).getPath();
			mv.addObject("thingImage", thingImage);
			mv.addObject("thing", thing);
			break;
		case ThingStory:
			ThingStoryImage thingStoryImage = this.thingStoryImageService
					.getFirstImageByStoryThingId(thingStory.getId());
			if (thingStoryImage != null) {
				mv.addObject("StoryImage", thingStoryImage.getPath());
			} else {
				mv.addObject("StoryImage", "images/story_image.png");
			}
			mv.addObject("thingStory", thingStory);
			break;
		case Help:
			HelpImage helpImage = this.helpImageStoryService.getFirstImageByHelpId(help.getId());
			if (helpImage != null) {
				mv.addObject("HelpImage", helpImage.getPath());
			} else {
				mv.addObject("HelpImage", "images/help_image.png");
			}
			mv.addObject("help", help);
			break;
		}

		mv.addObject("fUser", fUser);
		mv.addObject("tUser", tUser);
		mv.addObject("cList", cList);
		mv.addObject("ChatGroup", cg);
		return mv;
	}

	/**
	 * 废除
	 * 
	 * @param request
	 * @param chatGroupId
	 * @return
	 */
	public ModelAndView withThing(HttpServletRequest request, @RequestParam("CHATGROUPID") String chatGroupId) {
		ModelAndView mv = new ModelAndView("chat/trade");
		ChatGroup cg = this.chatGroupService.getBaseDao().find(chatGroupId);
		Thing thing = null;
		if (cg != null) {
			thing = cg.getThing();
		} else {
			throw new NullEntityException();
		}
		List<Chat> cList = this.chatService.getListByGroupId(chatGroupId);
		User fUser = (User) request.getSession().getAttribute("user");
		User tUser = null;
		// 卖家的角度
		if (fUser.getId().equals(thing.getUser().getId())) {
			tUser = cg.getUser();
		} else {
			// 买家角度
			tUser = thing.getUser();
		}
		String thingImage = this.thingImageService.getFirstImageByThingId(thing.getId()).getPath();
		mv.addObject("thingImage", thingImage);
		mv.addObject("thing", thing);
		mv.addObject("fUser", fUser);
		mv.addObject("tUser", tUser);
		mv.addObject("cList", cList);
		mv.addObject("ChatGroup", cg);
		return mv;
	}

	/**
	 * 设置占用socket
	 * 
	 * @param toUserid
	 *            发送用户id
	 * @param useUserid
	 *            使用用户id
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/occupy")
	@ResponseBody
	public String OccupySessionV2(HttpServletRequest request, String useUserid, String toUserid, String usage) {
		// 获取要发送用户的session
		WebSocketSession session = socketSessionManager.getSession(useUserid);
		if (session != null && session.isOpen()) {
			socketSessionManager.registerUseage(session.getId(), usage);
		}
		return StandardResponseBody.Default(1, "成功", new HashMap<String, Object>());
	}
	/**
	 * 废除
	 * 
	 * @param request
	 * @param useUserid
	 * @param toUserid
	 * @param thingId
	 * @return
	 */
	// public String OccupySession(HttpServletRequest request,String
	// useUserid,String toUserid,String thingId){
	// //获取要发送用户的session
	// WebSocketSession session = socketSessionManager.getSession(useUserid);
	// if(session != null && session.isOpen()){
	// socketSessionManager.addOccupy(session.getId(), toUserid,thingId);
	// }
	// return StandardResponseBody.Default(1, "成功", new
	// HashMap<String,Object>());
	// }

}
